package fm.dongman.animefm.view.fragment

import android.content.Context
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import fm.dongman.animefm.R
import fm.dongman.animefm.contractlib.contract.RegisterContract
import fm.dongman.animefm.view.util.ActivityHelper
import fm.dongman.animefm.view.util.ToastHelper
import fm.dongman.modellib.StaticArea.Injection
import fm.dongman.modellib.source.RegisterRepository
import fm.dongman.presenterlib.presenter.RegisterPresenter
import kotlinx.android.synthetic.main.fragment_register.*
import org.jetbrains.anko.enabled
import org.jetbrains.anko.onClick
import java.lang.ref.WeakReference

/**
 * 登录/注册/修改/重置密码界面
 * Created by shize on 2017/11/14.
 */
class RegisterFragment : BaseFragment(), RegisterContract.IRegisterView {
    private lateinit var mPresenter: RegisterContract.IRegisterPresenter // 全局数据控制器
    private var mFlagType = TYPE_REGISTER // 注册类型

    private val mTimeHandler = TimeHandler(this) // 验证码计时器

    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View {
        val fragment = inflater!!.inflate(R.layout.fragment_register, container, false)
        RegisterPresenter(this, Injection.provideRegisterRepository())
        return fragment
    }

    override fun initData() {
        if (arguments != null) {
            mFlagType = arguments.getString(FLAG_TYPE).toInt()
        }
    }

    override fun bindData() {
        when (mFlagType) {
            TYPE_FORGET -> bindForget() // 找密
            TYPE_REGISTER -> bindRegister()// 注册
        }
    }

    /**
     * 绑定找密
     */
    private fun bindForget() {
        mBtnRegRegister.text = "找回密码"
        mBtnRegGetCode.onClick {
            // 发送验证码
            sendValidateCode()
        }
        mBtnRegRegister.onClick {
            if (checkPwd()) return@onClick
            val isRegister = mPresenter.modify(mEtRegPhoneNum.text.toString(), mEtRegPassword.text.toString(), mEtRegVerifyCode.text.toString(), TYPE_FORGET)
            if (!isRegister) {
                ToastHelper.getInstance(activity).showWarn("密码格式不正确！")
                return@onClick
            }
            mBtnRegRegister?.enabled = false
        }
    }

    /**
     * 绑定注册
     */
    private fun bindRegister() {
        mBtnRegGetCode.onClick {
            // 发送验证码
            sendValidateCode()
        }
        mBtnRegRegister.onClick {
            if (checkPwd()) return@onClick
            val isRegister = mPresenter.register(mEtRegPhoneNum.text.toString(), mEtRegPassword.text.toString(), mEtRegVerifyCode.text.toString())
            if (!isRegister) {
                ToastHelper.getInstance(activity).showWarn("密码格式不正确！")
                return@onClick
            }
            mBtnRegRegister?.enabled = false
        }
    }

    private fun checkPwd(): Boolean {
        if (mEtRegPassword.text.toString() != mEtRegPasswordCheck.text.toString()) {
            ToastHelper.getInstance(activity).showWarn("确认密码不一致！")
            return true
        }
        return false
    }

    /**
     * 发送验证码
     */
    private fun sendValidateCode() {
        val isSend = mPresenter.validate(mEtRegPhoneNum.text.toString(), mFlagType)
        if (!isSend) {
            ToastHelper.getInstance(activity).showWarn("请输入正确的手机号格式")
            return
        }
        mBtnRegGetCode?.enabled = false
    }

    /**
     * 显示倒计时
     * @param time 时间
     */
    private fun displayTime(time: String) {
        mBtnRegGetCode?.text = time
    }

    override fun showNoNetwork() {
        ToastHelper.getInstance(activity).showError("没有网络！")
    }

    override fun showValidateSucceed() {
        // 验证码发送成功
        ToastHelper.getInstance(activity).showSucceed("发送成功")
        mTimeHandler.sendEmptyMessageDelayed(HANDLER_MSG, HANDLER_DELAYED) // 发送倒计时
    }

    override fun showValidateFailed() {
        // 验证码发送失败
        ToastHelper.getInstance(activity).showError("发送失败")
        mBtnRegGetCode?.enabled = true
    }

    override fun showRegisterSucceed() {
        // 注册成功
        when(mFlagType){
            TYPE_FORGET->
                ToastHelper.getInstance(activity).showSucceed("找密成功")
            TYPE_REGISTER->
                ToastHelper.getInstance(activity).showSucceed("注册成功")
        }
        ActivityHelper.backActivity(activity)
    }

    override fun showRegisterFailed() {
        // 注册失败
        when(mFlagType){
            TYPE_FORGET->
                ToastHelper.getInstance(activity).showError("找密失败")
            TYPE_REGISTER->
                ToastHelper.getInstance(activity).showError("注册失败")
        }
        mBtnRegGetCode?.enabled = true
        mBtnRegRegister?.enabled = true
    }

    override fun showModifyPasswordSucceed() {
        // 修改/重置密码成功
        ToastHelper.getInstance(activity).showSucceed("修改/重置密码成功")
        ActivityHelper.backActivity(activity)
    }

    override fun showModifyPasswordFailed() {
        // 修改/重置密码失败
        ToastHelper.getInstance(activity).showError("修改/重置密码失败")
    }

    override fun showBindPhoneResult(msg: String) {
        // 绑定/修改手机号
        ToastHelper.getInstance(activity).showSucceed("" + msg)
    }

    override fun setPresenter(presenter: RegisterContract.IRegisterPresenter) {
        mPresenter = presenter
    }

    override fun showRefreshFailed() {}

    override fun isActive(): Boolean = isAdded

    override fun getViewContext(): Context = activity

    private class TimeHandler constructor(fragment: RegisterFragment) : Handler() {
        private var mWeakFragment: WeakReference<RegisterFragment> = WeakReference(fragment)
        private var mTime: Int = 0 // 倒计时时间

        override fun handleMessage(msg: Message?) {
            super.handleMessage(msg)
            val fragment: RegisterFragment = mWeakFragment.get() ?: return
            if (mTime < TIME_OUT)
                mTime++
            if (mTime >= TIME_OUT) {
                fragment.displayTime("获取验证码")
                fragment.mBtnRegGetCode?.enabled = true
                mTime = 0
                return
            }
            val strTime = (TIME_OUT - mTime).toString() + "s后可重发"
            fragment.displayTime(strTime)
            sendEmptyMessageDelayed(HANDLER_MSG, HANDLER_DELAYED)
        }
    }

    companion object {
        private val FLAG_TYPE = "fm.dongman.animefm.register.flagType" // Type key
        val TYPE_REGISTER = RegisterRepository.TYPE_REGISTER // 注册
        val TYPE_LOGIN = RegisterRepository.TYPE_LOGIN // 登录
        val TYPE_MODIFY = RegisterRepository.TYPE_MODIFY // 修改密码
        val TYPE_FORGET = RegisterRepository.TYPE_FORGET // 忘记/重置密码
        val TYPE_MODIFY_PHONE = RegisterRepository.TYPE_MODIFY_PHONE // 绑定/修改手机号

        val HANDLER_MSG = 0 // 发送 handler msg
        val HANDLER_DELAYED = 1000L // 发送 handler 的时间间隔
        val TIME_OUT = 60 // 验证码发送间隔 s

        fun getInstance(flagType: String): RegisterFragment {
            val fragment = RegisterFragment()
            val bundle = Bundle()
            bundle.putString(FLAG_TYPE, flagType)
            fragment.arguments = bundle
            return fragment
        }
    }
}